package com.pangu.typeHandler;

import com.pangu.constant.enums.IIntEnum;
import com.pangu.utils.EnumCodeUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Linbizhao
 * @description:
 * @since 2023/11/21 11:27
 */
public class CustomIntEnumTypeHandler<E extends Enum<?> & IIntEnum<?>> extends BaseTypeHandler<IIntEnum<?>> {
    private Class<E> iEnum;

    public CustomIntEnumTypeHandler(Class<E> iEnum) {
        if (iEnum == null) {
            throw new IllegalArgumentException("参数类型不能为空.");
        } else {
            this.iEnum = iEnum;
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, IIntEnum<?> iEnum, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, iEnum.getCode());
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return EnumCodeUtils.codeOf(this.iEnum, rs.getInt(columnName));
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return EnumCodeUtils.codeOf(this.iEnum, rs.getInt(columnIndex));
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return EnumCodeUtils.codeOf(this.iEnum, cs.getInt(columnIndex));
    }
}
